import React, { useEffect, useState } from 'react';
import { Table, Card, message, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import axios from 'axios';
import PurchaseCharts from './PurchaseCharts';

interface PurchaseRecord {
  id: number;
  transaction_id: string;
  product_id: string;
  purchase_date: string;
  status: string;
  price: number;
  currency: string;
  country_code: string;
  store_country_code: string;
  app_name: string;
  app_version: string;
  launch_count: number;
  is_trial: boolean;
  expiry_date: string;
  environment: string;
  updated_at: string;
}

interface PurchaseRecordsProps {
  token: string;
}

const PurchaseRecords: React.FC<PurchaseRecordsProps> = ({ token }) => {
  const [data, setData] = useState<PurchaseRecord[]>([]);
  const [loading, setLoading] = useState(false);

  const columns: ColumnsType<PurchaseRecord> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '交易ID',
      dataIndex: 'transaction_id',
      key: 'transaction_id',
    },
    {
      title: '产品ID',
      dataIndex: 'product_id',
      key: 'product_id',
    },
    {
      title: '购买日期',
      dataIndex: 'purchase_date',
      key: 'purchase_date',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price: number, record: PurchaseRecord) => 
        `${price} ${record.currency}`,
    },
    {
      title: '国家',
      dataIndex: 'country_code',
      key: 'country_code',
    },
    {
      title: '商店国家',
      dataIndex: 'store_country_code',
      key: 'store_country_code',
    },
    {
      title: '应用名称',
      dataIndex: 'app_name',
      key: 'app_name',
    },
    {
      title: '应用版本',
      dataIndex: 'app_version',
      key: 'app_version',
    },
    {
      title: '启动次数',
      dataIndex: 'launch_count',
      key: 'launch_count',
    },
    {
      title: '试用版',
      dataIndex: 'is_trial',
      key: 'is_trial',
      render: (isTrial: boolean) => (isTrial ? '是' : '否'),
    },
    {
      title: '过期日期',
      dataIndex: 'expiry_date',
      key: 'expiry_date',
      render: (date: string) => date ? new Date(date).toLocaleString() : '-',
    },
    {
      title: '环境',
      dataIndex: 'environment',
      key: 'environment',
    },
  ];

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        console.log('正在请求购买记录数据，token:', token);
        const response = await axios.get('/api/purchases', {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
        });
        console.log('API响应:', response);
        if (response.data) {
          setData(response.data);
        } else {
          message.error('返回数据格式不正确');
        }
      } catch (error: any) {
        console.error('API请求错误:', error);
        if (error.response) {
          console.error('错误响应:', error.response.data);
          message.error(`获取数据失败: ${error.response.data.error || '未知错误'}`);
        } else if (error.request) {
          console.error('请求错误:', error.request);
          message.error('无法连接到服务器，请检查网络连接');
        } else {
          console.error('错误:', error.message);
          message.error(`请求失败: ${error.message}`);
        }
      } finally {
        setLoading(false);
      }
    };

    if (token) {
      fetchData();
    }
  }, [token]);

  return (
    <Space direction="vertical" size="middle" style={{ display: 'flex', width: '100%' }}>
      <PurchaseCharts token={token} />
      <Card title="购买记录">
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ x: true }}
          size="small"
          rowClassName={(record, index) => index % 2 === 0 ? 'table-row-light' : 'table-row-dark'}
          pagination={{
            defaultPageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['10', '20', '50', '100'],
            position: ['bottomRight']
          }}
        />
      </Card>
    </Space>
  );
};

export default PurchaseRecords; 